<template>
	<view id="s_side_bar">
		<scroll-view scroll-y="true" style="height: 100%;" :scroll-top="scrollTop" bindscrolltolower="scrolltolower"
			:enhanced="true" :show-scrollbar="false" scroll-with-animation enable-back-to-top>
			<slot />
			<view class="brace" :class="{env:safe_area_inset_bottom}"></view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { ref, watch, getCurrentInstance, onMounted, onUpdated, } from 'vue';
	import { debounce } from '@/utils/common/index.js';

	const props = defineProps({
		safe_area_inset_bottom: {
			type: Boolean,
			default: true,
		},
		active: {
			type: Number,
			default: 0,
		}
	});

	const scrollTop = ref(0);
	const that = getCurrentInstance();
	let totalHeight = 0;
	// let selectorQueryNodesRef = null;

	onMounted(() => {

		// selectorQueryNodesRef = uni.createSelectorQuery().in(that);
		getTotalHeight();
	})
	onUpdated(() => { getTotalHeight(); })

	watch(() => props.active, (newValue) => {
		updateScroll(Number(newValue))
	})
	const updateScroll = debounce(function(active) {
		uni.createSelectorQuery().in(that).selectAll('.s_side_bar_item').fields({
			size: true,
		}, data => {
			var offsetTop = data.slice(0, active).reduce(function(prev, curr) {
				return prev + curr.height;
			}, 0);
			scrollTop.value = offsetTop - (totalHeight - data[active].height) / 2;
		}).exec();
	}, 100);


	function getTotalHeight() {
		uni.createSelectorQuery().in(that).select('#s_side_bar').fields({
			size: true,
		}, data => {
			totalHeight = data.height;
		}).exec();
	}
</script>

<style lang="scss" scoped>
	#s_side_bar {
		height: 100%;
		widows: 100%;
	}

	.brace {
		box-sizing: border-box;
		height: 34px;
	}

	.env {
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 IOS<11.2*/
		padding-bottom: env(safe-area-inset-bottom);
		/*兼容 IOS>11.2*/
	}

	/*隐藏滚动条*/
	::-webkit-scrollbar {
		width: 0;
		height: 0;
	}
</style>